<template>
    <!-- <h1>商品详情</h1> -->

    <van-nav-bar
        title="商品详情"
        left-text="返回"
        left-arrow
        @click-left="$router.back()"
    />

    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="item in proDetail.banners" ::key="item">
            <van-image :src="item" />
        </van-swipe-item>
    </van-swipe>

    <van-icon @click="addCart" name="cart-o" color="#1989fa" size="50" />

    <div>
        <p>商品分类: {{ proDetail.category }}</p>
        <p>商品品牌: {{ proDetail.brand }}</p>
        <p>商品名: {{ proDetail.proname }}</p>
        <p>商品价格: {{ proDetail.originprice }}</p>
        <p>{{ proDetail.desc }}</p>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { Ref } from "vue";
import { useRoute } from "vue-router";
import { getProDetail } from "@/api/pro";
import { getCartAdd } from "@/api/cart";
import { showSuccessToast, showFailToast } from "vant";

// 创建一个路由信息集合 (this.$route)
const route = useRoute();

// 添加商品到购物车
async function addCart() {
    const { data } = await getCartAdd({
        userid: window.localStorage.getItem("userid") + "",
        proid: route.query.id as string,
        num: "1",
    });

    if (data.code !== "200") {
        // 提示添加购物车成功
        return showFailToast(data.message);
    }

    // 提醒用户 添加购物车成功
    showSuccessToast(data.message);
}

interface IProDetail {
    banners: string[];
    proid: string;
    category: string;
    brand: string;
    proname: string;
    originprice: number;
    sales: number;
    stock: number;
    desc: string;
    issale: number;
    isrecommend: number;
    discount: number;
    isseckill: number;
    img1: string;
    img2: string;
    img3: string;
    img4: string;
}

// 存储商品详情
const proDetail: Ref<IProDetail> = ref({
    banners: [],
    proid: "",
    category: "",
    brand: "",
    proname: "",
    originprice: -1,
    sales: -1,
    stock: -1,
    desc: "",
    issale: -1,
    isrecommend: -1,
    discount: -1,
    isseckill: -1,
    img1: "",
    img2: "",
    img3: "",
    img4: "",
});

// 在 生命周期中发送请求, 获取商品详情
onMounted(async () => {
    const { data } = await getProDetail(route.query.id);

    proDetail.value = data.data;
    proDetail.value.banners = proDetail.value.banners[0].split(",");

    // console.log(proDetail.value);
});
</script>
